<!--
  适配后台的commonSelect组件

  用法：
    <common-select
      v-model="commonSelectVisible"
      selectKey="selectSmartTable"
      selectMode="1"
      @success="(rows) => {  }"
    ></common-select>

  说明：
    v-model：绑定一个boolean值，用来显示或隐藏commonselect；
    selectKey：后台commonSelect配置文件里的指定的section的id值；
    selectMode：单选还是多选，0 单选，1 多选；
    @success：commonSelect关闭后的触发的事件，传一个参数rows，表示选中的记录

-->
<template>
  <vxe-modal
    ref="commonSelectModal"
    v-model="visible"
    :resize="true"
    width="1024"
    height="600"
    :title="models.section.name"
    :show-zoom="true"
    :destroy-on-close="true"
    :show-footer="true"
    @close="cancel"
  >
    <div class="common-select-container">
      <div class="searchBox">
        <el-form ref="searchForm" :inline="true" :model="search">
          <el-form-item
            v-for="item in finalSearchColumns"
            :key="item.column"
            :label="item.name"
            :prop="item.column"
          >
            <el-input v-model="search[item.column]" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item style="margin-top: -2px">
            <el-button type="primary" @click="tableSearch">查询</el-button>
            <el-button
              type="info"
              @click="(search = {}), tableSearch()"
            >重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <qm-table
        ref="qmTable"
        :urls="urls"
        :show-menu="false"
        :show-toolbar="false"
        :show-checkbox="multiple"
        :show-radio="!multiple"
        :options="calOptions"
        :pager-options="{ pageSize: 5 }"
        :before-query="beforeQuery"
      >
        <qm-table-column
          v-for="item in finalColumns"
          :key="item.field"
          :field="item.field"
        >{{ item.name }}</qm-table-column>
      </qm-table>
    </div>

    <template #footer>
      <el-row>
        <el-col :span="24" style="text-align: right;">
          <el-button type="primary" @click="returnResult">确定</el-button>
          <el-button type="info" @click="cancel">关闭</el-button>
        </el-col>
      </el-row>
    </template>
  </vxe-modal>
</template>

<script>
import _ from 'lodash'
import request from '@/utils/request'

export default {
  name: 'CommonSelectList',
  props: {
    // commonSelect 配置文件的 section 标签的 id
    selectKey: {
      type: String,
      required: true
    },
    // 0 单选，1 多选
    selectMode: {
      type: Number | String,
      default: '0'
    },
    value: Boolean,
    onBeforeQuery: {
      type: Function,
      required: false
    }
  },
  data() {
    return {
      models: {
        commonSelectHeader: '',
        commonSelectSearch: '',
        section: {},
        selectMode: '0'
      },
      search: {},
      controlData: {},
      urls: {
        query: ''
      },
      visible: false
    }
  },
  computed: {
    multiple() {
      return this.models.selectMode === '1' || this.models.selectMode === 1
    },
    calOptions() {
      if (this.multiple) {
        return { checkboxConfig: { highlight: true, trigger: 'row' }}
      }
      return {
        checkboxConfig: { highlight: false },
        radioConfig: { highlight: true, trigger: 'row' }
      }
    },
    finalColumns() {
      const columns = this.models.section.columns
      if (!columns) {
        return []
      }
      return this.getColumns(columns)
    },
    finalSearchColumns() {
      return this.models.section.sectionSearchItem || []
    }
  },
  watch: {
    value(visible) {
      this[visible ? 'show' : 'hide']()
    }
  },
  methods: {
    beforeQuery(params) {
      if (this.onBeforeQuery) {
        this.onBeforeQuery(params)
      } else {
        params.query = _.extend({}, this.search)
      }
    },
    tableSearch() {
      const params = {
        start: 0,
        query: {}
      }
      params.query = _.extend({}, this.search)
      this.$refs['qmTable'].fetchListData(params)
    },
    getColumns(text) {
      const columns = []
      const TH_START = '<th'
      const TH_END = '</th>'
      let thStartIdx = text.indexOf(TH_START)
      let thEndIdx = text.indexOf(TH_END, thStartIdx)

      while (thStartIdx !== -1 && thEndIdx !== -1) {
        const th = text.substring(thStartIdx, thEndIdx + TH_END.length + 1)
        columns.push(this.filterColumn(th))

        thStartIdx = text.indexOf(TH_START, thEndIdx + TH_END.length + 1)
        thEndIdx = text.indexOf(TH_END, thStartIdx)
      }

      return columns
    },
    filterColumn(th) {
      const TH_START = '<th'
      const TH_START_END = '>'
      const TH_END = '</th>'
      const FIELD_START = 'field="'
      const FIELD_END = '"'
      const thStartIdx = th.indexOf(TH_START)
      const thStartEndIdx = th.indexOf(TH_START_END, thStartIdx)
      const thEndIdx = th.indexOf(TH_END, thStartEndIdx)
      const fieldStartIdx = th.indexOf(FIELD_START, thStartIdx)
      const fieldEndIdx = th.indexOf(
        FIELD_END,
        fieldStartIdx + FIELD_START.length
      )

      const field = th
        .substring(fieldStartIdx + FIELD_START.length, fieldEndIdx)
        .trim()
      const name = th.substring(thStartEndIdx + 1, thEndIdx).trim()
      return { name: name, field: field }
    },
    fetchModelData() {
      return new Promise((rs, rj) => {
        request({
          url: '/commonSelect/getModel',
          method: 'post',
          data: { id: this.selectKey, selectMode: this.selectMode }
        })
          .then(r => {
            this.models = r.models
            this.urls = r.urls
            this.controlData = r.controlData
            rs(true)
          })
          .catch(e => {
            rj(false)
          })
      })
    },
    show() {
      this.fetchModelData().then(r => {
        this.visible = true
      })
    },
    hide() {
      this.visible = false
    },
    cancel() {
      this.$emit('input', false)
      this.$emit('cancel')
    },
    returnResult() {
      const rows = this.$refs['qmTable'].getSelectedRows()
      this.$emit('input', false)
      this.$emit('success', rows)
    }
  }
}
</script>

<style></style>
